﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        SerialPort sp1 = new SerialPort();
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            
            string[] myarr = SerialPort.GetPortNames();
            for (int i = 0; i < myarr.Length; i++)
            {
                comboBox1.Items.Add(myarr[i]);
            }
            comboBox1.SelectedIndex = 0;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string mystr = comboBox1.SelectedItem.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!sp1.IsOpen) //如果没打开   
            {
                MessageBox.Show("请先打开串口！", "Error");
                return;
            }

            String strSend = "123";
            sp1.WriteLine(strSend);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //serialPort1.IsOpen
            if (!sp1.IsOpen)
            {
                try
                {
                    //设置串口号
                    string serialName = comboBox1.SelectedItem.ToString();
                    sp1.PortName = serialName;

                    //设置各“串口设置”
                    string strBaudRate = "9600";
                    string strDateBits = "8";
                    Int32 iBaudRate = Convert.ToInt32(strBaudRate);
                    Int32 iDateBits = Convert.ToInt32(strDateBits);

                    sp1.BaudRate = iBaudRate;       //波特率
                    sp1.DataBits = iDateBits;       //数据位
                    sp1.StopBits = StopBits.One;    //停止位
                    sp1.Parity = Parity.None;


                    if (sp1.IsOpen == true)//如果打开状态，则先关闭一下
                    {
                        sp1.Close();
                    }

                    sp1.Open();     //打开串口
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error:" + ex.Message, "Error");
                    return;
                }
            }
            else
            {
                sp1.Close();                    //关闭串口
                MessageBox.Show("关闭了串口");
            }
        }



        private void timer1_Tick(object sender, EventArgs e)
        {
            int x = 0;
            x++;
            if (x == 5)
            {
                button2.PerformClick();
                x = 0;
            }
        }
    }
}
